/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
 *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left),
 * right(right) {}
 * };
 */
class Solution {
public:
    void dfs(TreeNode* root, const int& targetSum, long long sum, int& ans) {
        if (root == nullptr)
            return;
        sum += root->val;
        if (sum == targetSum) {
            ans++;
        }
        dfs(root->left, targetSum, sum, ans);
        dfs(root->right, targetSum, sum, ans);
    }
    int pathSum(TreeNode* root, int targetSum) {
        if (root == nullptr)
            return 0;
        queue<TreeNode*> q;
        q.push(root);
        int ans = 0;
        while (!q.empty()) {
            TreeNode* cur = q.front();
            q.pop();
            dfs(cur, targetSum, 0, ans);
            if (cur->left)
                q.push(cur->left);
            if (cur->right)
                q.push(cur->right);
        }
        return ans;
    }
};